
var GoogleAdvert = new Class({
    Implements: Options,
    options: {
        'tagid':''
    },
    groupid:null, //
    categoryid:null,
    subTable:'', //
    initialize: function(opts) {
        this.setOptions(opts);

        this.panel = document.id(this.options.tagid)
        if(!this.panel) return;
        this.panel.empty();

        this.createGoogleTable();

        this.googleRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            onRequest: function() {
                new ShowBox().say('Loading...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.fillContent(data);
            }.bind(this)
        }).send('table=google&ex=groups&nc=' + Date.now());

    },
    createGoogleTable: function() {
        this.content = new Element('div#content');
        this.listData = new Element('table#listData[rules=groups]');

        var buttonUpdate = new Element('button[text=Update Google Files][style=font-weight:bold;color:red;padding:1px 2px;]',{
            'events': {
                'click': this.updateFiles.bind(this),
                'focus': function() {this.blur();}
            }
        })

        new Element('span[style=padding:0 0 10px 30px;]').adopt(
            new Element('b[html=Refresh count :&nbsp;&nbsp;]'),
            buttonUpdate,
            new Element('span#loader[style=background:transparent url(../webstat/img/loader-big.gif) no-repeat scroll 0 0;]')
        ).inject(this.panel);

        this.panel.adopt(
            new Element('div.tl[html=<div class="tr"><div>&nbsp;</div></div>]'),
            this.content.adopt(this.listData),
            new Element('div.bl[html=<div class="br"><div>&nbsp;</div></div>]')
        )

        this.createHead();
    },
    updateFiles: function(ev) {
        ev.stop()

        var r = confirm("Не запускайте часто update google files тормозит работу www.compuvest.com\nУверен что хочешь этого?");
        if(r != true) {
            alert("You pressed Cancel!")
            return
        }     
 
        new Request({
            url: '/Admin/transactions/MakeGoogleFile',
            method: 'get',
            onRequest: function() {
                document.id('loader').setStyle('padding', '20px')
            },
            onComplete: function() {
                document.id('loader').setStyle('padding', '0')
            }
        }).send('google=update')
    },
    createHead: function() {

        this.listData.adopt(
            new Element('thead').adopt(
                new Element('tr').adopt(
                    new Element('th.brdCol.w15[html=&nbsp;]'),
                    new Element('th.brdCol.w15[html=&nbsp;]'),
                    new Element('th.brdCol.w80[text=File Name]'),
                    new Element('th.brdCol.w150[text=Google group name]'),
                    new Element('th.brdCol.w50[text=Count]'),
                    new Element('th.brdCol.w50[text=cpc(max)]'),
                    new Element('th.brdCol.w50[text=cont(cpc)]')
                )
            ),
            new Element('tfoot').adopt(
                new Element('tr').adopt(
                    new Element('th.tdFull[colspan=7][html=&nbsp;]')
                )
            ),
            new Element('tbody')
        );

    },
    fillContent: function(data) {
        var group,tbody,tr,tdo,tde,color=false,tagid;

        tbody = this.listData.getElement('tbody');
        tbody.empty();

        for(var i = 0; i < data.groups.length; i++) {
            group = data.groups[i];

            tr = new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]',{
                'events': {
                    'mouseenter': function() {this.addClass('rowHover');},
                    'mouseleave': function() {this.removeClass('rowHover');}
                }
            });

            tagid = 'ggl_' + i;
            tdo = new Element('td.imgCol').adopt(
                new Element('a.plus[href=javascript:;][html=&nbsp;][title=Open Category]',{
                    'events': {
                        'click': this.makeCategory.bind(this, group.id, tagid),
                        'focus': function() {this.blur();}
                    }
                })
            );
            tde = new Element('td.imgCol').adopt(
                new Element('a.edit[href=javascript:;][html=&nbsp;][title=Edit group]',{
                    'events': {
                        'click': this.makeGroupChange.bind(this, group.id),
                        'focus': function() {this.blur();}
                    }
                })
            );

            tbody.adopt(
                tr.adopt(
                    tdo,
                    tde,
                    new Element('td.brdCol.center.w80[text=' + group.fname + ']'),
                    new Element('td.brdCol.left.w150[text=' + group.name + ']'),
                    new Element('td.brdCol.center.w50[text=' + group.cnt + ']'),
                    new Element('td.brdCol.center.w50[text=' + group.cpcmax + ']'),
                    new Element('td.brdCol.center.w50[text=' + group.cpccnt + ']')
                )
            );

            tbody.adopt(
                new Element('tr#x' + tagid + '[style=display:none;]').adopt(
                    new Element('td[html=&nbsp;]'),
                    new Element('td#d' + tagid + '[colspan=7][style=padding-top:0;]')
                )
            );

        }// for

    },
    makeCategory: function(groupid, tagid, ev) {

        this.groupid = groupid;
        var xcuc = document.id('x' + tagid);
        var dcuc = document.id('d' + tagid);
        if(ev.target.hasClass('plus')) {
            ev.target.removeClass('plus').addClass('minus');

            dcuc.empty();

            new Element('label#glab[text=Group Selected: ').adopt(
                new Element('input[type=checkbox][value=y]',{
                    'events': {
                        'click': function(ev) {
                            var sel = ev.target.get('checked');

                            this.categoryRequest.send('table=google&ex=getcat&groupid=' + (sel ? groupid : '') + '&nc=' + Date.now());
                        }.bind(this),
                        'focus': function() {this.blur();}
                    }
                }),
                new Element('small[html=&nbsp;Select checked category]')
            ).inject(dcuc);

            var div = new Element('div#gcat').inject(dcuc);

            this.categoryRequest = new Request({
                url: '/Admin/webstat/getFromMySQL',
                method: 'get',
                onRequest: function() {
                    ev.target.addClass('load');
                },
                onComplete: function(resp) {
                    var data = [];
                    try {
                        data = eval('[' + resp + ']');
                    }
                    catch(err) { alert('Error...\n' + err); return; }
                    ev.target.removeClass('load');

                    this.showCategory(data, div);
                }.bind(this)
            }).send('table=google&ex=getcat&nc=' + Date.now());

            xcuc.set('styles', {'display':'','background-color':'#ffffff'});
        }
        else {
            ev.target.removeClass('minus').addClass('plus');

            xcuc.setStyle('display', 'none');
        }
    },
    showCategory: function(data, tagid) {

        tagid.empty();
        var divsub = new Element('div'),divcat = new Element('div');
        for(var i = 0; i < data.length; i++) {
            divcat.adopt(
                new  Element('tt[text=[]'),
                new  Element('a[href=javascript:;][text=' + data[i].name + ']',{
                    'events': {
                        'click': this.getSubcat.bind(this, data[i].id, data[i].name, divsub),
                        'focus': function() {this.blur();}
                    }
                }),
                new  Element('tt[text=]]')
            );
        }
        tagid.adopt(divcat, divsub);

    },
    getSubcat: function(catid, catName, tagid) {

        this.categoryid = catid;
        tagid.empty();

        this.subcatRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('Opening...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.showSubcategory(data, tagid, catName);
            }.bind(this)
        }).send('table=google&ex=getscat&cid=' + catid + '&nc=' + Date.now());

    },
    showSubcategory: function(data, tagid, catName) {

        var vends = new Hash(), cats = new Hash(), legend = '';
        data.sub.each(function(subcat) {
            if(!vends.has(subcat.alias)) {
                vends.set(subcat.alias, subcat.vid);
                legend += '<tt>' + subcat.alias + '</tt> - <em>' + subcat.vname + '</em>, ';
            }
            //
            if(!cats.has(subcat.cname)) {
                cats.set(subcat.cname,subcat.cid);
            }

        });
        //
        tagid.adopt(
            new  Element('hr'),
            new  Element('tt[text=' + catName + '][style=color:#800000;font-weight:bold;]'),
            new  Element('div#legend[html=<b>Legend:</b> ' + legend + ']')
        );

        var tbody = new Element('tbody'),td,trd,haveBorder = false,catSum=0,catAmnt=0,cbox,chk,notGroup;
        var trhead = new Element('tr').adopt(
            new Element('th.brdCol.left.w50').adopt(
                new Element('tt[text=Subcategory]'),
                new Element('br'),
                new Element('input[type=checkbox]',{
                    'events': {
                        'click': this.groupAllToggle.bind(this),
                        'focus': function() {this.blur();}
                    }
                }).store('grp', this.groupid),
                new Element('small[html=&nbsp;&nbsp;Toggle All]')
            )
        );
        var trbot = new Element('tr').adopt(
            new Element('th.brdCol.left.w50').adopt(
                new  Element('button[text= Save ]',{
                    'events': {
                        'click': this.saveGroup.bind(this),
                        'focus': function() {this.blur();}
                    }
                }).store('grp', this.groupid)
            )
        );

        cats.each(function(catid, catName) {
            trd = new Element('tr').adopt(
                new Element('td.brdCol.left.w50[html=<h4>' + catName + '</h4>]')
            );
            catSum = 0;
            vends.each(function(vendid, vendAlias) {

                cbox = this.getCheckBox(data.sub, catid, vendid);
                chk =  this.getCheckGroup(data.grp, catid, vendid);
                notGroup = chk.gid != this.groupid;

                td = new Element('td.brdCol.center.w15[html=&nbsp;]');
                if(chk.gid && cbox.cnt && notGroup) {
                    td.addClass('bgreen');
                }

                if(cbox.cnt) {
                    td.set('html','<b style="cursor:pointer;" title="' + (notGroup ? chk.names : 'here') + '">' + cbox.cnt + '</b><br/>' +
                           '<input ' +
                           (notGroup ? '' : 'checked="checked"') + ' name="' + this.groupid + '_' + vendid + '" value="' + catid + '_' + vendid +
                           '" type="checkbox" />')
                    catSum += cbox.cnt;
                }
                trd.adopt(td);

                if(!haveBorder) {
                    trhead.adopt(
                        new Element('th.brdCol.center.w15').adopt(
                            new Element('tt[text=Toggle ' + vendAlias + ']'),
                            new Element('br'),
                            new Element('input#' + (this.groupid + '_' + vendid) + '[type=checkbox]',{
                                'events': {
                                    'click': this.groupToggle.bind(this),
                                    'focus': function() {this.blur();}
                                }
                            })
                        )
                    );
                    catAmnt += catSum;
                    trbot.adopt(
                        new Element('th.brdCol.center.w15[html=<b>&nbsp;</b>]')
                    );
                }
            }, this);
            haveBorder = true;
            trd.adopt(
                new Element('td.brdCol.center.w15[html=<b>' + catSum + '</b>]')
            );
            tbody.adopt(trd);
        }, this);

        trhead.adopt(
            new Element('th.brdCol.center.w15[html=&nbsp;]')
        );
        trbot.adopt(
            new Element('th.brdCol.center.w15[html=<b>' + catAmnt + '</b>]')
        );

        this.subTable = new Element('table#listData[rules=groups]');
        this.subTable.adopt(
            new Element('thead').adopt(trhead),
            new Element('tfoot').adopt(trbot),
            tbody
        )
        tagid.adopt(this.subTable);

    },
    getCheckBox: function(cats, cid, vid) {
        var result = {};
        for(var i = 0; i < cats.length; i++) {
            if(cats[i].cid == cid && cats[i].vid == vid) {
                result = {als:cats[i].alias,cnt:cats[i].cnt};
                break;
            }
        }
        return result;
    },
    getCheckGroup: function(grps, cid, vid) {
        var result = {}, names = '', idx = 0, notFind = true;
        for(var i = 0; i < grps.length; i++) {
            if(grps[i].cid == cid && grps[i].vid == vid) {
                names += (idx++ > 0 ? ' ' : '') + grps[i].gname;
                if(notFind) {
                    notFind = false;
                    result = {names: '', gid: grps[i].gid, vid: grps[i].vid, cid: grps[i].cid};
                }
            }
        }
        result.names = names;
        return result;
    },
    saveGroup: function(ev) {
        var checkme = this.subTable.getElements('input[name^=' + ev.target.retrieve('grp') + ']');
        var val = '&cb=';
        checkme.each(function(el,idx) {
            val += (idx++ > 0 ? ',' : '') + el.get('value') + '_' + (el.get('checked') ? 1 : 0);
        });

        this.saveRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'post',
            onRequest: function() {
                new ShowBox().say('Saving...');
                new Loader().show();
            },
            onComplete: function() {
                new Loader().hide();
            }
        }).send('table=google&ex=save&groupid=' + this.groupid + '&catid=' + this.categoryid + '&nc=' + Date.now() + val);
    },
    groupToggle: function(ev) {
        var checkme = this.subTable.getElements('input[name=' + ev.target.get('id') + ']'),docheck;
        if(ev.target.retrieve('togg')) {
            docheck = false;
            ev.target.store('togg', docheck);
        }
        else {
            docheck = true;
            ev.target.store('togg', docheck);
        }
        checkme.each(function(el) {
            el.set('checked', docheck);
        });
    },
    groupAllToggle: function(ev) {
        var checkme = this.subTable.getElements('input[name^=' + ev.target.retrieve('grp') + ']'),docheck;
        if(ev.target.retrieve('togg')) {
            docheck = false;
            ev.target.store('togg', docheck);
        }
        else {
            docheck = true;
            ev.target.store('togg', docheck);
        }
        checkme.each(function(el) {
            el.set('checked', docheck);
        });
    },
    makeGroupChange: function(groupid, ev) {
        ev.stop();

        this.groupid = groupid;
        new GroupChange({
            'groupid': groupid,
            'targetid': ev.target,
            onReload: function() {

                this.googleRequest.send('table=google&ex=groups&nc=' + Date.now());
            }.bind(this)
        });
    }
});

var GroupChange = new Class({
    Implements: [Events, Options],
    options: {
        groupid: 0,
        targetid: null
    },
    initialize: function(options) {
        this.setOptions(options);
        if(!this.options.groupid) return;

        this.groupchange = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'post',
            onRequest: function() {
                this.options.targetid.removeClass('edit').addClass('load');
            }.bind(this),
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('[' + resp + ']');
                }
                catch(err) { alert('Error...\n' + err); return; }
                this.options.targetid.removeClass('load').addClass('edit');

                this.makeForm(data);
            }.bind(this)
        }).send('table=google&ex=getgroup&groupid=' + this.options.groupid + '&nc=' + Date.now());

    },
    makeForm: function(group) {

        //make body
        this.fileName = new Element('input[type=text][size=18][maxlength=15][style=width:80px;][value=' + group.fname + ']');
        this.groupName = new Element('input[type=text][size=25][maxlength=25][style=width:130px;][value=' + group.name + ']');
        this.cpcMax = new Element('input[type=text][size=8][maxlength=6][style=width:40px;][value=' + group.cpcmax + ']');
        this.cpcCnt = new Element('input[type=text][size=8][maxlength=6][style=width:40px;][value=' + group.cpccnt + ']');
        this.active = new Element('input[type=checkbox]').set('checked', group.active);

        this.update = new Element('a.update.closeThis[href=javascript:;][html=&nbsp;][title=Update Group]');
        this.create = new Element('a.create.closeThis[href=javascript:;][html=&nbsp;][title=Create New Group]');
        this.erase = new Element('a.erase.closeThis[href=javascript:;][html=&nbsp;][title=Erase Group]');

        var table = new Element('table#ggroup').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(
                    new Element('th.col[text=FileName]'),
                    new Element('th.col[text=Google Group Name]'),
                    new Element('th.col[text=cpc(max)]'),
                    new Element('th.col[text=content cpc]')
                ),
                new Element('tr').adopt(
                    new Element('td.sep[colspan=4][html=<hr/>]')
                ),
                new Element('tr').adopt(
                    new Element('td.col').adopt(this.fileName),
                    new Element('td.col').adopt(this.groupName),
                    new Element('td.col').adopt(this.cpcMax),
                    new Element('td.col').adopt(this.cpcCnt)
                ),
                new Element('tr').adopt(
                    new Element('td.sep[colspan=4][html=<hr/>]')
                ),
                new Element('tr').adopt(
                    new Element('td.col').adopt(
                        this.active,
                        new Element('em[html=&nbsp;Active]')
                    ),
                    new Element('td.col').adopt(
                        this.update,
                        new Element('em[text=Update]')
                    ),
                    new Element('td.col').adopt(
                        this.create,
                        new Element('em[text=Create]')
                    ),
                    new Element('td').adopt(
                        this.erase,
                        new Element('em[text=Erase]')
                    )
                )
            )
        );

        new ModalBox({
            width: 610,
            modal: {
                background: '#555'
            },
            onOpen: function() {
                this.update.addEvents({'click': this.updateGroup.bind(this, group.id), 'focus': function() {this.blur();} });
                this.create.addEvents({'click': this.createGroup.bind(this), 'focus': function() {this.blur();} });
                this.erase.addEvents({'click': this.eraseGroup.bind(this, group.id), 'focus': function() {this.blur();} });
            }.bind(this)
        }).doBox('<h2>Google Group: ' + group.name + '</h2>', new Element('center').adopt(table));

    },
    updateGroup: function(groupid) {

        // update group to database
        this.groupchange.send(
            'table=google&ex=updategroup&groupid=' + groupid +
            '&name=' + this.groupName.get('value') +
            '&fname=' + this.fileName.get('value') +
            '&cpcmax=' + this.cpcMax.get('value') +
            '&cpcnt=' + this.cpcCnt.get('value') +
            '&actv=' + (this.active.get('checked') ? 1 : 0) +
            '&nc=' + Date.now());

        this.fireEvent('reload');
    },
    createGroup: function() {

        // create new group to database
        this.groupchange.send(
            'table=google&ex=creategroup' +
            '&name=' + this.groupName.get('value') +
            '&fname=' + this.fileName.get('value') +
            '&cpcmax=' + this.cpcMax.get('value') +
            '&cpcnt=' + this.cpcCnt.get('value') +
            '&actv=' + (this.active.get('checked') ? 1 : 0) +
            '&nc=' + Date.now());

        this.fireEvent('reload');
    },
    eraseGroup: function(groupid) {

        this.groupchange.send('table=google&ex=erasegroup&groupid=' + groupid + '&nc=' + Date.now());

        this.fireEvent('reload');
    }
});

